// ================== DBC词法分析器 (Tokenizer) ==================
class DBCTokenizer {
    constructor(content) {
        this.content = content;
        this.position = 0;
        this.line = 1;
        this.column = 1;
        this.tokens = [];
        this.current = 0;
    }

    // 词法分析，将DBC内容转换为标记
    tokenize() {
        this.tokens = [];
        this.position = 0;
        this.line = 1;
        this.column = 1;

        while (this.position < this.content.length) {
            this.skipWhitespace();
            
            if (this.position >= this.content.length) break;

            const char = this.currentChar();
            
            // 跳过注释行 (//)
            if (char === '/' && this.peek() === '/') {
                this.skipLine();
                continue;
            }

            // 字符串字面量
            if (char === '"') {
                this.readString();
                continue;
            }

            // 数字（包括科学计数法）
            if (this.isDigit(char) || (char === '-' && this.isDigit(this.peek()))) {
                this.readNumber();
                continue;
            }

            // 标识符和关键字
            if (this.isAlpha(char) || char === '_') {
                this.readIdentifier();
                continue;
            }

            // 单字符标记
            if (this.isSeparator(char)) {
                this.addToken('SEPARATOR', char);
                this.advance();
                continue;
            }

            // 算术符号
            if (char === '+' || char === '-') {
                this.addToken('SIGN', char);
                this.advance();
                continue;
            }

            // 跳过未知字符
            this.advance();
        }

        this.addToken('EOF', '');
        return this.tokens;
    }

    currentChar() {
        return this.position < this.content.length ? this.content[this.position] : '\0';
    }

    peek(offset = 1) {
        const pos = this.position + offset;
        return pos < this.content.length ? this.content[pos] : '\0';
    }

    advance() {
        if (this.position < this.content.length) {
            if (this.content[this.position] === '\n') {
                this.line++;
                this.column = 1;
            } else {
                this.column++;
            }
            this.position++;
        }
        return this.currentChar();
    }

    skipWhitespace() {
        while (this.isWhitespace(this.currentChar())) {
            this.advance();
        }
    }

    skipLine() {
        while (this.currentChar() !== '\n' && this.currentChar() !== '\0') {
            this.advance();
        }
        if (this.currentChar() === '\n') {
            this.advance();
        }
    }

    readString() {
        const start = this.position;
        this.advance(); // 跳过开始的引号
        
        let value = '';
        while (this.currentChar() !== '"' && this.currentChar() !== '\0') {
            if (this.currentChar() === '\\') {
                this.advance();
                // 处理转义字符
                switch (this.currentChar()) {
                    case 'n': value += '\n'; break;
                    case 't': value += '\t'; break;
                    case 'r': value += '\r'; break;
                    case '\\': value += '\\'; break;
                    case '"': value += '"'; break;
                    default: value += this.currentChar(); break;
                }
            } else {
                value += this.currentChar();
            }
            this.advance();
        }
        
        if (this.currentChar() === '"') {
            this.advance(); // 跳过结束的引号
        }
        
        this.addToken('STRING', value);
    }

    readNumber() {
        let value = '';
        let hasDecimal = false;
        let hasExponent = false;

        // 处理负号
        if (this.currentChar() === '-') {
            value += this.currentChar();
            this.advance();
        }

        // 读取数字部分
        while (this.isDigit(this.currentChar()) || 
               (!hasDecimal && this.currentChar() === '.') ||
               (!hasExponent && (this.currentChar() === 'e' || this.currentChar() === 'E'))) {
            
            if (this.currentChar() === '.') {
                hasDecimal = true;
            } else if (this.currentChar() === 'e' || this.currentChar() === 'E') {
                hasExponent = true;
                value += this.currentChar();
                this.advance();
                // 处理指数符号
                if (this.currentChar() === '+' || this.currentChar() === '-') {
                    value += this.currentChar();
                    this.advance();
                }
                continue;
            }
            
            value += this.currentChar();
            this.advance();
        }

        const type = hasDecimal || hasExponent ? 'FLOAT' : 'INTEGER';
        this.addToken(type, value);
    }

    readIdentifier() {
        let value = '';
        while (this.isAlphaNumeric(this.currentChar()) || this.currentChar() === '_') {
            value += this.currentChar();
            this.advance();
        }
        this.addToken('IDENTIFIER', value);
    }

    addToken(type, value) {
        this.tokens.push({
            type,
            value,
            line: this.line,
            column: this.column - value.length
        });
    }

    isWhitespace(char) {
        return char === ' ' || char === '\t' || char === '\n' || char === '\r';
    }

    isDigit(char) {
        return char >= '0' && char <= '9';
    }

    isAlpha(char) {
        return (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z');
    }

    isAlphaNumeric(char) {
        return this.isAlpha(char) || this.isDigit(char);
    }

    isSeparator(char) {
        return ':,|@()[]'.includes(char);
    }
}

// ================== DBC数据模型 ==================
class CANSignal {
    constructor(name, startBit, length, byteOrder, signedness, factor, offset, min, max, unit, comment = '') {
        this.name = name;
        this.startBit = startBit;
        this.length = length;
        this.byteOrder = byteOrder; // 'Intel' or 'Motorola'
        this.signedness = signedness; // 'signed' or 'unsigned'
        this.factor = factor;
        this.offset = offset;
        this.min = min;
        this.max = max;
        this.unit = unit;
        this.comment = comment;
        this.choices = new Map(); // 值表 VAL_
        this.multiplexInfo = null; // 多路复用信息
    }

    setComment(comment) {
        this.comment = comment;
    }

    setChoices(choices) {
        this.choices = new Map(Object.entries(choices));
    }

    setMultiplexInfo(info) {
        this.multiplexInfo = info;
    }

    // 计算物理值
    calculatePhysicalValue(rawValue) {
        return rawValue * this.factor + this.offset;
    }

    // 从CAN数据中提取信号值
    extractValue(canData) {
        // 这里可以实现从CAN字节数组中提取信号值的逻辑
        // 根据startBit, length, byteOrder等参数
        // 暂时返回0，具体实现需要根据CAN信号的位操作
        return 0;
    }
}

class CANFrame {
    constructor(name, canId, dlc, comment = '') {
        this.name = name;
        this.canId = canId;
        this.dlc = dlc;
        this.comment = comment;
        this.signals = new Map(); // name -> CANSignal
        this.transmitters = []; // 发送节点
        this.period = 0; // 发送周期（毫秒）
    }

    addSignal(signal) {
        this.signals.set(signal.name, signal);
    }

    removeSignal(signalName) {
        return this.signals.delete(signalName);
    }

    getSignal(signalName) {
        return this.signals.get(signalName);
    }

    hasSignal(signalName) {
        return this.signals.has(signalName);
    }

    getAllSignals() {
        return Array.from(this.signals.values());
    }

    setComment(comment) {
        this.comment = comment;
    }

    setPeriod(period) {
        this.period = period;
    }

    setTransmitters(transmitters) {
        this.transmitters = transmitters;
    }

    // 获取帧类型
    getFrameType() {
        return this.canId > 0x7FF ? 'Extended' : 'Standard';
    }
}

class CANDatabase {
    constructor(filename = '') {
        this.filename = filename;
        this.frames = new Map(); // canId -> CANFrame
        this.framesByName = new Map(); // name -> CANFrame
        this.nodes = new Set(); // 节点列表
        this.version = '';
        this.comments = new Map(); // 全局注释
        this.attributes = new Map(); // 属性定义
        this.valueTables = new Map(); // 值表定义
        this.warnings = []; // 解析警告
    }

    addFrame(frame) {
        this.frames.set(frame.canId, frame);
        this.framesByName.set(frame.name, frame);
    }

    removeFrame(canId) {
        const frame = this.frames.get(canId);
        if (frame) {
            this.frames.delete(canId);
            this.framesByName.delete(frame.name);
            return true;
        }
        return false;
    }

    getFrame(canId) {
        return this.frames.get(canId);
    }

    getFrameByName(name) {
        return this.framesByName.get(name);
    }

    hasFrame(canId) {
        return this.frames.has(canId);
    }

    getAllFrames() {
        return Array.from(this.frames.values());
    }

    addNode(nodeName) {
        this.nodes.add(nodeName);
    }

    addWarning(message, line = 0) {
        this.warnings.push({ message, line });
    }

    getStatistics() {
        const frameCount = this.frames.size;
        let signalCount = 0;
        for (const frame of this.frames.values()) {
            signalCount += frame.signals.size;
        }
        return { frameCount, signalCount, nodeCount: this.nodes.size };
    }
}

// ================== DBC语法解析器 (Parser) ==================
class DBCParser {
    constructor(tokenizer) {
        this.tokenizer = tokenizer;
        this.tokens = [];
        this.current = 0;
        this.database = new CANDatabase();
        this.currentFrame = null;
    }

    parse() {
        this.tokens = this.tokenizer.tokenize();
        this.current = 0;
        this.database = new CANDatabase();

        console.log('开始解析DBC，共', this.tokens.length, '个标记');

        try {
            while (!this.isAtEnd()) {
                this.parseTopLevelStatement();
            }
        } catch (error) {
            console.error('解析错误:', error);
            this.database.addWarning(`解析错误: ${error.message}`, this.getCurrentLine());
        }

        return this.database;
    }

    parseTopLevelStatement() {
        const token = this.peek();
        
        if (!token || token.type === 'EOF') {
            return;
        }

        switch (token.value) {
            case 'VERSION':
                this.parseVersion();
                break;
            case 'NS_':
                this.parseNamespace();
                break;
            case 'BS_':
                this.parseBitTiming();
                break;
            case 'BU_':
                this.parseNodes();
                break;
            case 'BO_':
                this.parseMessage();
                break;
            case 'CM_':
                this.parseComment();
                break;
            case 'BA_DEF_':
                this.parseAttributeDefinition();
                break;
            case 'BA_':
                this.parseAttributeValue();
                break;
            case 'VAL_':
                this.parseValueTable();
                break;
            case 'BO_TX_BU_':
                this.parseTransmitters();
                break;
            default:
                // 跳过不支持的语句
                this.skipUntilNextStatement();
                break;
        }
    }

    parseVersion() {
        this.consume('IDENTIFIER', 'VERSION');
        const version = this.consume('STRING', '期望版本字符串');
        this.database.version = version.value;
        console.log('解析版本:', version.value);
    }

    parseNamespace() {
        this.consume('IDENTIFIER', 'NS_');
        this.consume('SEPARATOR', ':');
        // 跳过命名空间内容直到下一个语句
        while (!this.isAtEnd() && !this.isNextStatement()) {
            this.advance();
        }
    }

    parseBitTiming() {
        this.consume('IDENTIFIER', 'BS_');
        this.consume('SEPARATOR', ':');
        // 跳过位时序配置
        while (!this.isAtEnd() && !this.isNextStatement()) {
            this.advance();
        }
    }

    parseNodes() {
        this.consume('IDENTIFIER', 'BU_');
        this.consume('SEPARATOR', ':');
        
        // 读取所有节点名称
        while (!this.isAtEnd() && this.peek().type === 'IDENTIFIER') {
            const nodeName = this.advance().value;
            this.database.addNode(nodeName);
            console.log('添加节点:', nodeName);
        }
    }

    parseMessage() {
        this.consume('IDENTIFIER', 'BO_');
        
        const canId = this.consumeNumber('期望CAN ID');
        const name = this.consume('IDENTIFIER', '期望消息名称').value;
        this.consume('SEPARATOR', ':');
        const dlc = this.consumeNumber('期望DLC');
        
        // 读取发送节点（可选）
        const transmitters = [];
        while (!this.isAtEnd() && this.peek().type === 'IDENTIFIER' && !this.isNextStatement()) {
            transmitters.push(this.advance().value);
        }

        // 创建消息帧
        const frame = new CANFrame(name, canId, dlc);
        frame.setTransmitters(transmitters);
        this.currentFrame = frame;
        
        console.log(`解析消息: ${name} (ID: 0x${canId.toString(16)}, DLC: ${dlc})`);

        // 解析信号
        while (!this.isAtEnd() && this.peek().value === 'SG_') {
            this.parseSignal();
        }

        this.database.addFrame(frame);
        this.currentFrame = null;
    }

    parseSignal() {
        this.consume('IDENTIFIER', 'SG_');
        
        const signalName = this.consume('IDENTIFIER', '期望信号名称').value;
        
        // 检查多路复用信息
        let multiplexInfo = null;
        if (this.peek().type === 'IDENTIFIER') {
            const muxToken = this.peek().value;
            if (muxToken === 'M' || muxToken.startsWith('m')) {
                multiplexInfo = this.advance().value;
            }
        }

        this.consume('SEPARATOR', ':');
        
        const startBit = this.consumeNumber('期望起始位');
        this.consume('SEPARATOR', '|');
        const length = this.consumeNumber('期望长度');
        this.consume('SEPARATOR', '@');
        const byteOrder = this.consumeNumber('期望字节序');
        const signedness = this.consume('SIGN', '期望符号').value;

        this.consume('SEPARATOR', '(');
        const factor = this.consumeFloat('期望因子');
        this.consume('SEPARATOR', ',');
        const offset = this.consumeFloat('期望偏移');
        this.consume('SEPARATOR', ')');

        this.consume('SEPARATOR', '[');
        const min = this.consumeFloat('期望最小值');
        this.consume('SEPARATOR', '|');
        const max = this.consumeFloat('期望最大值');
        this.consume('SEPARATOR', ']');

        const unit = this.consume('STRING', '期望单位').value;

        // 读取接收节点
        const receivers = [];
        while (!this.isAtEnd() && this.peek().type === 'IDENTIFIER' && !this.isNextStatement()) {
            receivers.push(this.advance().value);
        }

        // 创建信号
        const signal = new CANSignal(
            signalName,
            startBit,
            length,
            byteOrder === 1 ? 'Intel' : 'Motorola',
            signedness === '-' ? 'signed' : 'unsigned',
            factor,
            offset,
            min,
            max,
            unit
        );

        if (multiplexInfo) {
            signal.setMultiplexInfo(multiplexInfo);
        }

        if (this.currentFrame) {
            this.currentFrame.addSignal(signal);
            console.log(`  添加信号: ${signalName} (${startBit}|${length})`);
        }
    }

    parseComment() {
        this.consume('IDENTIFIER', 'CM_');
        
        if (this.peek().type === 'STRING') {
            // 全局注释
            const comment = this.advance().value;
            this.database.comments.set('global', comment);
        } else if (this.peek().value === 'BO_') {
            // 消息注释
            this.advance(); // BO_
            const canId = this.consumeNumber('期望CAN ID');
            const comment = this.consume('STRING', '期望注释字符串').value;
            
            const frame = this.database.getFrame(canId);
            if (frame) {
                frame.setComment(comment);
            }
        } else if (this.peek().value === 'SG_') {
            // 信号注释
            this.advance(); // SG_
            const canId = this.consumeNumber('期望CAN ID');
            const signalName = this.consume('IDENTIFIER', '期望信号名称').value;
            const comment = this.consume('STRING', '期望注释字符串').value;
            
            const frame = this.database.getFrame(canId);
            if (frame && frame.hasSignal(signalName)) {
                frame.getSignal(signalName).setComment(comment);
            }
        }

        // 跳过分号
        if (this.peek().type === 'SEPARATOR' && this.peek().value === ';') {
            this.advance();
        }
    }

    parseAttributeDefinition() {
        // 跳过属性定义
        this.skipUntilNextStatement();
    }

    parseAttributeValue() {
        this.consume('IDENTIFIER', 'BA_');
        
        const attrName = this.consume('STRING', '期望属性名').value;
        
        // 处理消息周期时间
        if (attrName === 'GenMsgCycleTime' || attrName === 'CycleTime') {
            if (this.peek().value === 'BO_') {
                this.advance(); // BO_
                const canId = this.consumeNumber('期望CAN ID');
                const period = this.consumeNumber('期望周期值');
                
                const frame = this.database.getFrame(canId);
                if (frame) {
                    frame.setPeriod(period);
                }
            }
        }

        // 跳过到分号
        this.skipUntilSemicolon();
    }

    parseValueTable() {
        this.consume('IDENTIFIER', 'VAL_');
        
        const canId = this.consumeNumber('期望CAN ID');
        const signalName = this.consume('IDENTIFIER', '期望信号名称').value;
        
        const choices = {};
        while (!this.isAtEnd() && this.peek().type !== 'SEPARATOR') {
            const value = this.consumeNumber('期望值');
            const description = this.consume('STRING', '期望描述').value;
            choices[value] = description;
        }

        const frame = this.database.getFrame(canId);
        if (frame && frame.hasSignal(signalName)) {
            frame.getSignal(signalName).setChoices(choices);
        }

        // 跳过分号
        if (this.peek().type === 'SEPARATOR' && this.peek().value === ';') {
            this.advance();
        }
    }

    parseTransmitters() {
        // 跳过发送节点定义
        this.skipUntilSemicolon();
    }

    // 辅助方法
    consume(expectedType, message) {
        if (this.check(expectedType)) {
            return this.advance();
        }
        throw new Error(`${message}，但得到 ${this.peek().type}:${this.peek().value} 在第 ${this.getCurrentLine()} 行`);
    }

    consumeNumber(message) {
        const token = this.peek();
        if (token.type === 'INTEGER' || token.type === 'FLOAT') {
            this.advance();
            return parseFloat(token.value);
        }
        throw new Error(`${message}，但得到 ${token.type}:${token.value} 在第 ${this.getCurrentLine()} 行`);
    }

    consumeFloat(message) {
        const token = this.peek();
        if (token.type === 'INTEGER' || token.type === 'FLOAT') {
            this.advance();
            return parseFloat(token.value);
        }
        throw new Error(`${message}，但得到 ${token.type}:${token.value} 在第 ${this.getCurrentLine()} 行`);
    }

    check(type) {
        if (this.isAtEnd()) return false;
        return this.peek().type === type;
    }

    advance() {
        if (!this.isAtEnd()) this.current++;
        return this.previous();
    }

    isAtEnd() {
        return this.peek().type === 'EOF';
    }

    peek() {
        return this.tokens[this.current] || { type: 'EOF', value: '', line: 0 };
    }

    previous() {
        return this.tokens[this.current - 1];
    }

    getCurrentLine() {
        return this.peek().line || 0;
    }

    isNextStatement() {
        const token = this.peek();
        const statements = ['VERSION', 'NS_', 'BS_', 'BU_', 'BO_', 'CM_', 'BA_DEF_', 'BA_', 'VAL_', 'BO_TX_BU_'];
        return statements.includes(token.value);
    }

    skipUntilNextStatement() {
        while (!this.isAtEnd() && !this.isNextStatement()) {
            this.advance();
        }
    }

    skipUntilSemicolon() {
        while (!this.isAtEnd() && !(this.peek().type === 'SEPARATOR' && this.peek().value === ';')) {
            this.advance();
        }
        if (this.peek().value === ';') {
            this.advance();
        }
    }
}

// ================== DBC编辑器主类 ==================
class DBCEditor {
    constructor() {
        this.database = new CANDatabase();
        this.selectedFrameId = null;
        this.selectedSignalName = null;
        this.messageIdCounter = 1;
        this.signalIdCounter = 1;
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadSampleData();
        console.log('DBC编辑器初始化完成');
        console.log('数据库统计:', this.database.getStatistics());
        this.updateTables();
        this.updateDbcPreview();
        
        // 自动选择第一个消息进行演示
        setTimeout(() => {
            const frames = this.database.getAllFrames();
            if (frames.length > 0 && !this.selectedFrameId) {
                console.log('自动选择第一个消息进行测试...');
                this.toggleFrameSelection(frames[0].canId);
            }
        }, 1000);
        
        // 添加调试功能
        setTimeout(() => {
            console.log('添加调试功能...');
            this.addDebugPanel();
        }, 500);
    }

    bindEvents() {
        // 文件上传事件
        document.getElementById('dbcFile').addEventListener('change', (e) => {
            this.loadDbcFile(e.target.files[0]);
        });

        // 数据计算事件
        document.getElementById('hexData').addEventListener('input', () => {
            this.calculatePhysicalValue();
        });
    }

    // 加载示例数据
    loadSampleData() {
        // 创建示例消息帧
        const engineFrame = new CANFrame('Engine_Data', 0x123, 8, '发动机数据帧');
        const speedFrame = new CANFrame('Vehicle_Speed', 0x456, 4, '车辆速度信息');

        // 创建示例信号
        const engineRpm = new CANSignal('Engine_RPM', 0, 16, 'Intel', 'unsigned', 0.25, 0, 0, 8000, 'rpm', '发动机转速');
        const engineTemp = new CANSignal('Engine_Temp', 16, 8, 'Intel', 'signed', 1, -40, -40, 150, '°C', '发动机温度');
        const vehicleSpeed = new CANSignal('Vehicle_Speed', 0, 16, 'Intel', 'unsigned', 0.1, 0, 0, 300, 'km/h', '车辆速度');

        // 添加信号到帧
        engineFrame.addSignal(engineRpm);
        engineFrame.addSignal(engineTemp);
        speedFrame.addSignal(vehicleSpeed);

        // 添加帧到数据库
        this.database.addFrame(engineFrame);
        this.database.addFrame(speedFrame);

        // 添加示例节点
        this.database.addNode('ECU1');
        this.database.addNode('ECU2');

        console.log('示例数据加载完成:', this.database.getStatistics());
    }

    // 更新CAN消息表格
    updateCanMessagesTable() {
        const tbody = document.querySelector('#canMessagesTable tbody');
        
        if (!tbody) {
            console.log('消息表格DOM元素还没有准备好，稍后重试...');
            setTimeout(() => this.updateCanMessagesTable(), 100);
            return;
        }
        
        tbody.innerHTML = '';

        const frames = this.database.getAllFrames();
        frames.forEach(frame => {
            const row = document.createElement('tr');
            const isSelected = this.selectedFrameId === frame.canId;
            if (isSelected) row.classList.add('selected');
            
            // 添加点击行选择功能
            row.style.cursor = 'pointer';
            row.onclick = (e) => {
                // 如果点击的不是输入框或按钮，则选择该行
                if (!e.target.matches('input, select, button, i')) {
                    this.toggleFrameSelection(frame.canId);
                }
            };
            
            const canIdHex = '0x' + frame.canId.toString(16).toUpperCase();
            const frameType = frame.getFrameType();
            
            row.innerHTML = `
                <td><input type="checkbox" ${isSelected ? 'checked' : ''} 
                    onchange="dbcEditor.toggleFrameSelection(${frame.canId})"></td>
                <td><input type="text" value="${frame.name}" 
                    onchange="dbcEditor.updateFrame(${frame.canId}, 'name', this.value)"></td>
                <td><input type="text" value="${canIdHex}" 
                    onchange="dbcEditor.updateFrame(${frame.canId}, 'canIdHex', this.value)"></td>
                <td><input type="number" value="${frame.canId}" 
                    onchange="dbcEditor.updateFrame(${frame.canId}, 'canIdDec', this.value)"></td>
                <td><select onchange="dbcEditor.updateFrame(${frame.canId}, 'type', this.value)">
                    <option value="Standard" ${frameType === 'Standard' ? 'selected' : ''}>Standard</option>
                    <option value="Extended" ${frameType === 'Extended' ? 'selected' : ''}>Extended</option>
                </select></td>
                <td><input type="number" min="1" max="8" value="${frame.dlc}" 
                    onchange="dbcEditor.updateFrame(${frame.canId}, 'dlc', this.value)"></td>
                <td><input type="text" value="${frame.comment}" 
                    onchange="dbcEditor.updateFrame(${frame.canId}, 'comment', this.value)"></td>
                <td><button class="btn btn-danger btn-sm" onclick="dbcEditor.deleteFrame(${frame.canId})">
                    <i class="fas fa-trash"></i></button></td>
            `;
            tbody.appendChild(row);
        });
    }

    // 更新CAN信号表格
    updateCanSignalsTable() {
        console.log('更新信号表格, 选中帧ID:', this.selectedFrameId);
        const tbody = document.querySelector('#canSignalsTable tbody');
        
        if (!tbody) {
            console.log('DOM元素还没有准备好，稍后重试...');
            setTimeout(() => this.updateCanSignalsTable(), 100);
            return;
        }
        
        tbody.innerHTML = '';

        // 获取要显示的信号
        let signalsToShow = [];
        if (this.selectedFrameId) {
            const selectedFrame = this.database.getFrame(this.selectedFrameId);
            if (selectedFrame) {
                signalsToShow = selectedFrame.getAllSignals();
            }
        } else {
            // 显示所有信号
            const frames = this.database.getAllFrames();
            frames.forEach(frame => {
                signalsToShow.push(...frame.getAllSignals());
            });
        }
        
        console.log('要显示的信号:', signalsToShow.length, signalsToShow);

        signalsToShow.forEach(signal => {
            const row = document.createElement('tr');
            const isSelected = this.selectedSignalName === signal.name;
            if (isSelected) row.classList.add('selected');
            
            // 确定模式 - 基于多路复用信息
            let mode = 'Signal';
            if (signal.multiplexInfo) {
                if (signal.multiplexInfo === 'M') {
                    mode = 'Multiplexor';
                } else if (signal.multiplexInfo.startsWith('m')) {
                    mode = 'Multiplexed';
                }
            }
            
            row.innerHTML = `
                <td><input type="checkbox" ${isSelected ? 'checked' : ''} 
                    onchange="dbcEditor.toggleSignalSelection('${signal.name}')"></td>
                <td><input type="text" value="${signal.name}" 
                    onchange="dbcEditor.updateSignal('${signal.name}', 'name', this.value)"></td>
                <td><select onchange="dbcEditor.updateSignal('${signal.name}', 'signedness', this.value)">
                    <option value="unsigned" ${signal.signedness === 'unsigned' ? 'selected' : ''}>unsigned</option>
                    <option value="signed" ${signal.signedness === 'signed' ? 'selected' : ''}>signed</option>
                </select></td>
                <td><select onchange="dbcEditor.updateSignal('${signal.name}', 'byteOrder', this.value)">
                    <option value="Intel" ${signal.byteOrder === 'Intel' ? 'selected' : ''}>Intel</option>
                    <option value="Motorola" ${signal.byteOrder === 'Motorola' ? 'selected' : ''}>Motorola</option>
                </select></td>
                <td><select onchange="dbcEditor.updateSignal('${signal.name}', 'mode', this.value)">
                    <option value="Signal" ${mode === 'Signal' ? 'selected' : ''}>Signal</option>
                    <option value="Multiplexor" ${mode === 'Multiplexor' ? 'selected' : ''}>Multiplexor</option>
                    <option value="Multiplexed" ${mode === 'Multiplexed' ? 'selected' : ''}>Multiplexed</option>
                </select></td>
                <td><input type="number" min="0" max="63" value="${signal.startBit}" 
                    onchange="dbcEditor.updateSignal('${signal.name}', 'startBit', this.value)"></td>
                <td><input type="number" min="1" max="64" value="${signal.length}" 
                    onchange="dbcEditor.updateSignal('${signal.name}', 'length', this.value)"></td>
                <td><input type="number" step="any" value="${signal.factor}" 
                    onchange="dbcEditor.updateSignal('${signal.name}', 'factor', this.value)"></td>
                <td><input type="number" step="any" value="${signal.offset}" 
                    onchange="dbcEditor.updateSignal('${signal.name}', 'offset', this.value)"></td>
                <td><input type="number" step="any" value="${signal.min}" 
                    onchange="dbcEditor.updateSignal('${signal.name}', 'min', this.value)"></td>
                <td><input type="number" step="any" value="${signal.max}" 
                    onchange="dbcEditor.updateSignal('${signal.name}', 'max', this.value)"></td>
                <td><input type="text" value="${signal.unit}" 
                    onchange="dbcEditor.updateSignal('${signal.name}', 'unit', this.value)"></td>
                <td><input type="text" value="${signal.comment}" 
                    onchange="dbcEditor.updateSignal('${signal.name}', 'comment', this.value)"></td>
                <td><button class="btn btn-danger btn-sm" onclick="dbcEditor.deleteSignal('${signal.name}')">
                    <i class="fas fa-trash"></i></button></td>
            `;
            tbody.appendChild(row);
        });

        // 更新信号计数
        this.updateSignalCount();
    }

    // 更新表格显示
    updateTables() {
        this.updateCanMessagesTable();
        this.updateCanSignalsTable();
        this.updateSignalPreview();
    }

    // 更新信号计数
    updateSignalCount() {
        let signalsToShow = [];
        if (this.selectedFrameId) {
            const selectedFrame = this.database.getFrame(this.selectedFrameId);
            if (selectedFrame) {
                signalsToShow = selectedFrame.getAllSignals();
            }
        } else {
            const frames = this.database.getAllFrames();
            frames.forEach(frame => {
                signalsToShow.push(...frame.getAllSignals());
            });
        }
        
        const countElement = document.getElementById('signalCount');
        if (countElement) {
            if (this.selectedFrameId) {
                const selectedFrame = this.database.getFrame(this.selectedFrameId);
                countElement.textContent = `${selectedFrame ? selectedFrame.name : ''}的信号: ${signalsToShow.length}`;
            } else {
                countElement.textContent = `总计: ${signalsToShow.length}`;
            }
        }
    }

    // 更新信号预览
    updateSignalPreview() {
        if (!this.selectedSignalName || !this.selectedFrameId) {
            this.clearSignalPreview();
            return;
        }

        const selectedFrame = this.database.getFrame(this.selectedFrameId);
        if (!selectedFrame) {
            this.clearSignalPreview();
            return;
        }

        const selectedSignal = selectedFrame.getSignal(this.selectedSignalName);
        if (!selectedSignal) {
            this.clearSignalPreview();
            return;
        }

        this.renderSignalLayout(selectedSignal);
        this.updateCalculationArea(selectedSignal);
    }

    // 渲染信号布局
    renderSignalLayout(signal) {
        const frameData = document.getElementById('frameData');
        const signalMask = document.getElementById('signalMask');

        // 创建8字节的数据布局
        const bytesHtml = [];
        const maskHtml = [];

        for (let byte = 0; byte < 8; byte++) {
            bytesHtml.push(`
                <div class="byte-row">
                    <span class="byte-label">字节 ${byte}</span>
                    <div class="bit-row">
                        ${this.generateBitCells(byte, signal, false)}
                    </div>
                </div>
            `);

            maskHtml.push(`
                <div class="byte-row">
                    <span class="byte-label">字节 ${byte}</span>
                    <div class="bit-row">
                        ${this.generateBitCells(byte, signal, true)}
                    </div>
                </div>
            `);
        }

        frameData.innerHTML = `<div class="frame-layout">${bytesHtml.join('')}</div>`;
        signalMask.innerHTML = `<div class="mask-layout">${maskHtml.join('')}</div>`;
    }

    // 生成位单元格
    generateBitCells(byteIndex, signal, isMask) {
        const cells = [];
        const startByte = Math.floor(signal.startBit / 8);
        const endBit = signal.startBit + signal.length - 1;
        const endByte = Math.floor(endBit / 8);

        for (let bit = 7; bit >= 0; bit--) {
            const globalBit = byteIndex * 8 + (7 - bit);
            const isSignalBit = globalBit >= signal.startBit && globalBit <= endBit;
            
            let className = 'bit-cell';
            if (isSignalBit) {
                className += isMask ? ' signal-mask' : ' signal-bit';
            }

            const content = isMask ? (isSignalBit ? '1' : '0') : '0';
            cells.push(`<span class="${className}">${content}</span>`);
        }

        return cells.join('');
    }

    // 更新计算区域
    updateCalculationArea(signal) {
        document.getElementById('factor').textContent = signal.factor;
        document.getElementById('offset').textContent = signal.offset;
    }

    // 清除信号预览
    clearSignalPreview() {
        document.getElementById('frameData').innerHTML = '<p>请选择一个信号来查看预览</p>';
        document.getElementById('signalMask').innerHTML = '<p>信号掩码将在这里显示</p>';
    }

    // 计算物理值
    calculatePhysicalValue() {
        const hexInput = document.getElementById('hexData').value;
        const selectedSignal = this.canSignals.find(s => s.selected);
        
        if (!hexInput || !selectedSignal) return;

        try {
            // 将十六进制转换为十进制
            const decValue = parseInt(hexInput, 16);
            document.getElementById('decData').textContent = decValue;
            document.getElementById('rawValue').textContent = decValue;

            // 提取信号值
            const signalValue = this.extractSignalValue(decValue, selectedSignal);
            
            // 计算物理值
            const physicalValue = (signalValue * selectedSignal.factor) + selectedSignal.offset;
            document.getElementById('physicalValue').textContent = physicalValue.toFixed(2);
            
        } catch (error) {
            console.error('计算错误:', error);
        }
    }

    // 从原始数据中提取信号值
    extractSignalValue(rawData, signal) {
        // 简化的信号提取逻辑
        const mask = (1 << signal.length) - 1;
        const shifted = rawData >> signal.startBit;
        return shifted & mask;
    }

    // 消息选择控制
    toggleMessageSelection(messageId) {
        console.log('=== 开始选择消息 ===');
        console.log('选择消息 ID:', messageId);
        console.log('当前selectedMessageId:', this.selectedMessageId);
        
        const message = this.canMessages.find(m => m.id === messageId);
        if (message) {
            console.log('找到消息:', message.name);
            
            // 取消其他消息的选择
            this.canMessages.forEach(m => m.selected = false);
            
            // 切换选择状态
            const wasSelected = message.selected;
            message.selected = !wasSelected;
            
            if (message.selected) {
                this.selectedMessageId = messageId;
                console.log('新选中消息 ID:', this.selectedMessageId);
            } else {
                this.selectedMessageId = null;
                console.log('取消选择，selectedMessageId设为null');
            }
            
            // 立即查找相关信号并打印
            const relatedSignals = this.canSignals.filter(s => s.messageId === this.selectedMessageId);
            console.log('过滤后的信号数量:', relatedSignals.length);
            console.log('过滤后的信号:', relatedSignals);
            
            console.log('=== 开始更新表格 ===');
            this.updateTables();
            console.log('=== 表格更新完成 ===');
        } else {
            console.log('没有找到消息 ID:', messageId);
        }
    }

    // 信号选择控制
    toggleSignalSelection(signalId) {
        const signal = this.canSignals.find(s => s.id === signalId);
        if (signal) {
            // 取消其他信号的选择
            this.canSignals.forEach(s => s.selected = false);
            signal.selected = !signal.selected;
            
            if (signal.selected) {
                this.selectedSignal = signal;
            } else {
                this.selectedSignal = null;
            }
            
            this.updateTables();
        }
    }

    // 更新消息数据
    updateMessage(id, field, value) {
        const message = this.canMessages.find(m => m.id === id);
        if (message) {
            if (field === 'canIdHex') {
                message.canIdHex = value;
                message.canIdDec = parseInt(value, 16);
            } else if (field === 'canIdDec') {
                message.canIdDec = parseInt(value);
                message.canIdHex = '0x' + parseInt(value).toString(16).toUpperCase();
            } else {
                message[field] = value;
            }
            
            this.updateTables();
            this.updateDbcPreview();
        }
    }

    // 更新信号数据
    updateSignal(id, field, value) {
        const signal = this.canSignals.find(s => s.id === id);
        if (signal) {
            if (['startBit', 'length', 'factor', 'offset', 'min', 'max'].includes(field)) {
                signal[field] = parseFloat(value);
            } else {
                signal[field] = value;
            }
            
            this.updateTables();
            this.updateDbcPreview();
        }
    }

    // 添加新消息
    addCanMessage() {
        const newId = Math.max(...this.canMessages.map(m => m.id), 0) + 1;
        const newMessage = {
            id: newId,
            name: `New_Message_${newId}`,
            canIdHex: '0x' + (0x100 + newId).toString(16).toUpperCase(),
            canIdDec: 0x100 + newId,
            type: 'Standard',
            dlc: 8,
            comment: '新消息',
            selected: false
        };
        
        this.canMessages.push(newMessage);
        this.updateTables();
        this.updateDbcPreview();
    }

    // 删除消息
    deleteMessage(id) {
        if (confirm('确定要删除这个消息吗？相关的信号也会被删除。')) {
            this.canMessages = this.canMessages.filter(m => m.id !== id);
            this.canSignals = this.canSignals.filter(s => s.messageId !== id);
            
            if (this.selectedMessageId === id) {
                this.selectedMessageId = null;
            }
            
            this.updateTables();
            this.updateDbcPreview();
        }
    }

    // 删除选中的消息
    removeCanMessage() {
        const selected = this.canMessages.filter(m => m.selected);
        if (selected.length === 0) {
            alert('请先选择要删除的消息');
            return;
        }
        
        if (confirm(`确定要删除 ${selected.length} 个消息吗？`)) {
            selected.forEach(message => this.deleteMessage(message.id));
        }
    }

    // 添加新信号
    addCanSignal() {
        if (!this.selectedMessageId) {
            alert('请先选择一个消息来添加信号');
            return;
        }
        
        const newId = Math.max(...this.canSignals.map(s => s.id), 0) + 1;
        const newSignal = {
            id: newId,
            messageId: this.selectedMessageId,
            name: `New_Signal_${newId}`,
            type: 'unsigned',
            byteOrder: 'Intel',
            mode: 'Signal',

            startBit: 0,
            length: 8,
            factor: 1,
            offset: 0,
            min: 0,
            max: 255,
            unit: '',
            comment: '新信号',
            selected: false
        };
        
        this.canSignals.push(newSignal);
        this.updateTables();
        this.updateDbcPreview();
    }

    // 删除信号
    deleteSignal(id) {
        if (confirm('确定要删除这个信号吗？')) {
            this.canSignals = this.canSignals.filter(s => s.id !== id);
            
            if (this.selectedSignal && this.selectedSignal.id === id) {
                this.selectedSignal = null;
            }
            
            this.updateTables();
            this.updateDbcPreview();
        }
    }

    // 删除选中的信号
    removeCanSignal() {
        const selected = this.canSignals.filter(s => s.selected);
        if (selected.length === 0) {
            alert('请先选择要删除的信号');
            return;
        }
        
        if (confirm(`确定要删除 ${selected.length} 个信号吗？`)) {
            selected.forEach(signal => this.deleteSignal(signal.id));
        }
    }

    // 更新DBC预览
    updateDbcPreview() {
        let dbcContent = 'VERSION ""\n\n\n';
        dbcContent += 'NS_ :\n\tNS_DESC_\n\tCM_\n\tBA_DEF_\n\tBA_\n\tVAL_\n\tCAT_DEF_\n\tCAT_\n\tFILTER\n\tBA_DEF_DEF_\n\tEV_DATA_\n\tENVVAR_DATA_\n\tSGTYPE_\n\tSGTYPE_VAL_\n\tBA_DEF_SGTYPE_\n\tBA_SGTYPE_\n\tSIG_TYPE_REF_\n\tVAL_TABLE_\n\tSIG_GROUP_\n\tSIG_VALTYPE_\n\tSIGTYPE_VALTYPE_\n\tBO_TX_BU_\n\tBA_DEF_REL_\n\tBA_REL_\n\tBA_DEF_DEF_REL_\n\tBU_SG_REL_\n\tBU_EV_REL_\n\tBU_BO_REL_\n\tSG_MUL_VAL_\n\n';
        dbcContent += 'BS_:\n\n';
        dbcContent += 'BU_: XXX\n\n\n';

        // 添加消息定义
        this.canMessages.forEach(message => {
            dbcContent += `BO_ ${message.canIdDec} ${message.name}: ${message.dlc} XXX\n`;
            
            // 添加该消息的信号
            const messageSignals = this.canSignals.filter(s => s.messageId === message.id);
            messageSignals.forEach(signal => {
                const byteOrder = signal.byteOrder === 'Intel' ? '1' : '0';
                const signType = signal.type === 'signed' ? '-' : '+';
                dbcContent += ` SG_ ${signal.name} : ${signal.startBit}|${signal.length}@${byteOrder}${signType} (${signal.factor},${signal.offset}) [${signal.min}|${signal.max}] "${signal.unit}" XXX\n`;
            });
            dbcContent += '\n';
        });

        // 添加注释
        this.canMessages.forEach(message => {
            if (message.comment) {
                dbcContent += `CM_ BO_ ${message.canIdDec} "${message.comment}";\n`;
            }
        });

        this.canSignals.forEach(signal => {
            if (signal.comment) {
                const message = this.canMessages.find(m => m.id === signal.messageId);
                if (message) {
                    dbcContent += `CM_ SG_ ${message.canIdDec} ${signal.name} "${signal.comment}";\n`;
                }
            }
        });

        document.getElementById('dbcContent').textContent = dbcContent;
        document.getElementById('dbcLineCount').textContent = dbcContent.split('\n').length;
    }

    // 加载DBC文件
    loadDbcFile(file) {
        if (!file) return;
        
        console.log(`开始加载DBC文件: ${file.name} (${file.size} 字节)`);
        
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const startTime = performance.now();
                const parseStats = this.parseDbcContent(e.target.result);
                const endTime = performance.now();
                const parseTime = (endTime - startTime).toFixed(2);
                
                // 构建详细的反馈消息
                const stats = this.database.getStatistics();
                let message = `DBC文件 "${file.name}" 加载完成！\n\n`;
                message += `📊 解析统计:\n`;
                message += `• 消息数: ${stats.frameCount}\n`;
                message += `• 信号数: ${stats.signalCount}\n`;
                message += `• 节点数: ${stats.nodeCount}\n`;
                message += `• 解析时间: ${parseTime}ms\n`;
                
                if (parseStats.errors.length > 0) {
                    message += `\n⚠️ 解析警告: ${parseStats.errors.length} 个问题\n`;
                    message += `详细信息请查看浏览器控制台。`;
                } else {
                    message += `\n✅ 解析完美，无警告！`;
                }
                
                alert(message);
                
                // 在控制台输出详细统计
                console.log(`DBC文件解析完成: ${file.name}`);
                console.log(`解析统计:`, parseStats);
                
            } catch (error) {
                console.error('DBC解析错误:', error);
                alert(`DBC文件解析失败: ${error.message}\n\n请检查文件格式是否正确。`);
            }
        };
        
        reader.onerror = () => {
            alert('文件读取失败，请重试。');
        };
        
        reader.readAsText(file, 'utf-8');
    }

    // 解析DBC内容（使用新的模块化架构）
    parseDbcContent(content) {
        console.log('开始解析DBC内容...');
        
        try {
            // 使用新的分词器和解析器
            const tokenizer = new DBCTokenizer(content);
            const parser = new DBCParser(tokenizer);
            
            // 解析并获取新的数据库
            this.database = parser.parse();
            this.database.filename = 'uploaded_file.dbc';
            
            // 重置选择状态
            this.selectedFrameId = null;
            this.selectedSignalName = null;

            // 更新界面
            this.updateTables();
            this.updateDbcPreview();

            // 获取统计信息
            const stats = this.database.getStatistics();
            console.log('解析完成，统计信息:', stats);

            // 如果有警告，显示它们
            if (this.database.warnings.length > 0) {
                console.warn('解析警告:');
                this.database.warnings.forEach(warning => {
                    console.warn(`第${warning.line}行: ${warning.message}`);
                });
            }

            return {
                totalLines: content.split('\n').length,
                messagesFound: stats.frameCount,
                signalsFound: stats.signalCount,
                errors: this.database.warnings
            };

        } catch (error) {
            console.error('DBC解析错误:', error);
            throw error;
        }
    }


        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            
            // 跳过空行和注释行
            if (!line || line.startsWith('//') || line.startsWith('VERSION') || 
                line.startsWith('NS_') || line.startsWith('BS_') || line.startsWith('BU_')) {
                continue;
            }

            try {
                // 解析消息定义 BO_ <ID> <Name>: <DLC> <Node>
                if (line.startsWith('BO_')) {
                    const messageMatch = line.match(messageRegex);
                    if (messageMatch) {
                        const [, canIdStr, name, dlc, node] = messageMatch;
                        
                        // 支持十六进制和十进制地址
                        let canIdDec;
                        if (canIdStr.startsWith('0x') || canIdStr.startsWith('0X')) {
                            canIdDec = parseInt(canIdStr, 16);
                        } else {
                            canIdDec = parseInt(canIdStr, 10);
                        }
                        
                        currentMessage = {
                            id: messageIdCounter++,
                            name: name.trim(),
                            canIdHex: '0x' + canIdDec.toString(16).toUpperCase(),
                            canIdDec: canIdDec,
                            type: canIdDec > 0x7FF ? 'Extended' : 'Standard',
                            dlc: parseInt(dlc),
                            comment: '',
                            selected: false
                        };
                        this.canMessages.push(currentMessage);
                        parseStats.messagesFound++;
                        
                        console.log(`解析消息: ${currentMessage.name} (ID: ${currentMessage.canIdHex})`);
                    } else {
                        parseStats.errors.push(`第${i+1}行: 无法解析消息定义 - ${line}`);
                    }
                }
                
                // 解析信号定义 SG_
                else if (line.trim().startsWith('SG_') && line.includes(':')) {
                    if (!currentMessage) {
                        parseStats.errors.push(`第${i+1}行: 发现信号但没有当前消息 - ${line}`);
                        continue;
                    }

                    let signalMatch = null;
                    let muxInfo = null;
                    let isMultiplexed = false;

                    // 先尝试多路复用信号匹配
                    signalMatch = line.match(muxSignalRegex);
                    if (signalMatch) {
                        muxInfo = signalMatch[2]; // M 或 m<value>
                        isMultiplexed = true;
                        console.log(`发现多路复用信号: ${signalMatch[1]} (${muxInfo})`);
                    } else {
                        // 尝试标准信号匹配
                        signalMatch = line.match(normalSignalRegex);
                        if (signalMatch) {
                            console.log(`发现标准信号: ${signalMatch[1]}`);
                        }
                    }

                    if (signalMatch) {
                        const offset = isMultiplexed ? 1 : 0; // 多路复用信号有额外的mux字段
                        
                        const name = signalMatch[1].trim();
                        const startBit = parseInt(signalMatch[2 + offset]);
                        const length = parseInt(signalMatch[3 + offset]);
                        const byteOrder = signalMatch[4 + offset];
                        const signType = signalMatch[5 + offset];
                        const factor = parseFloat(signalMatch[6 + offset]);
                        const offset_val = parseFloat(signalMatch[7 + offset]);
                        const min = parseFloat(signalMatch[8 + offset]);
                        const max = parseFloat(signalMatch[9 + offset]);
                        const unit = signalMatch[10 + offset].trim();
                        const node = signalMatch[11 + offset].trim();

                        // 确定信号模式
                        let mode = 'Signal';
                        if (isMultiplexed) {
                            if (muxInfo === 'M') {
                                mode = 'Multiplexor';
                            } else if (muxInfo.startsWith('m')) {
                                mode = 'Multiplexed';
                            }
                        }

                        const signal = {
                            id: signalIdCounter++,
                            messageId: currentMessage.id,
                            name: name,
                            type: signType === '-' ? 'signed' : 'unsigned',
                            byteOrder: byteOrder === '1' ? 'Intel' : 'Motorola',
                            mode: mode,
                            startBit: startBit,
                            length: length,
                            factor: factor,
                            offset: offset_val,
                            min: min,
                            max: max,
                            unit: unit,
                            comment: '',
                            selected: false
                        };

                        // 添加多路复用信息（如果需要的话，可以后续扩展）
                        if (isMultiplexed && muxInfo.startsWith('m')) {
                            signal.multiplexValue = muxInfo.substring(1); // 去掉'm'
                        }

                        this.canSignals.push(signal);
                        parseStats.signalsFound++;
                        
                        console.log(`成功解析信号: ${signal.name} (${signal.mode})`);
                    } else {
                        // 尝试更宽松的匹配来调试
                        console.warn(`第${i+1}行: 无法解析信号 - ${line}`);
                        
                        // 尝试分解行来调试
                        const parts = line.trim().split(/\s+/);
                        console.log('信号行分解:', parts);
                        
                        // 尝试最基本的信号匹配
                        const basicMatch = line.match(/^\s*SG_\s+(\w+)/);
                        if (basicMatch) {
                            console.log('至少找到信号名:', basicMatch[1]);
                            
                            // 创建一个基本的信号对象，使用默认值
                            const signal = {
                                id: signalIdCounter++,
                                messageId: currentMessage.id,
                                name: basicMatch[1],
                                type: 'unsigned',
                                byteOrder: 'Intel',
                                mode: 'Signal',
                                startBit: 0,
                                length: 8,
                                factor: 1,
                                offset: 0,
                                min: 0,
                                max: 255,
                                unit: '',
                                comment: `解析失败的信号 - 原始: ${line}`,
                                selected: false
                            };
                            
                            this.canSignals.push(signal);
                            parseStats.signalsFound++;
                            parseStats.errors.push(`第${i+1}行: 信号解析不完整，使用默认值 - ${line}`);
                        } else {
                            parseStats.errors.push(`第${i+1}行: 完全无法解析信号 - ${line}`);
                        }
                    }
                }
                
                // 解析消息注释 CM_ BO_ <ID> "<Comment>";
                else if (line.startsWith('CM_ BO_')) {
                    const commentMatch = line.match(/^CM_\s+BO_\s+(\w+)\s+"([^"]*)";\s*$/);
                    if (commentMatch) {
                        const [, canIdStr, comment] = commentMatch;
                        let canIdDec = canIdStr.startsWith('0x') ? parseInt(canIdStr, 16) : parseInt(canIdStr, 10);
                        const message = this.canMessages.find(m => m.canIdDec === canIdDec);
                        if (message) {
                            message.comment = comment;
                        }
                    }
                }
                
                // 解析信号注释 CM_ SG_ <MessageID> <SignalName> "<Comment>";
                else if (line.startsWith('CM_ SG_')) {
                    const commentMatch = line.match(/^CM_\s+SG_\s+(\w+)\s+([^\s]+)\s+"([^"]*)";\s*$/);
                    if (commentMatch) {
                        const [, canIdStr, signalName, comment] = commentMatch;
                        let canIdDec = canIdStr.startsWith('0x') ? parseInt(canIdStr, 16) : parseInt(canIdStr, 10);
                        const message = this.canMessages.find(m => m.canIdDec === canIdDec);
                        if (message) {
                            const signal = this.canSignals.find(s => s.messageId === message.id && s.name === signalName);
                            if (signal) {
                                signal.comment = comment;
                            }
                        }
                    }
                }
                
                // 解析值表 VAL_ (可选，基础支持)
                else if (line.startsWith('VAL_')) {
                    // 暂时跳过，但记录
                    console.log('发现值表定义:', line);
                }
                
            } catch (error) {
                parseStats.errors.push(`第${i+1}行解析异常: ${error.message} - ${line}`);
                console.error(`解析第 ${i + 1} 行时出错:`, error, line);
            }
        }

        // 输出解析统计
        console.log('=== DBC解析完成 ===');
        console.log(`总行数: ${parseStats.totalLines}`);
        console.log(`解析的消息数: ${parseStats.messagesFound}`);
        console.log(`解析的信号数: ${parseStats.signalsFound}`);
        console.log(`错误数: ${parseStats.errors.length}`);
        
        if (parseStats.errors.length > 0) {
            console.log('解析错误列表:');
            parseStats.errors.forEach(error => console.warn(error));
        }

        // 更新显示
        this.updateTables();
        this.updateDbcPreview();
        
        console.log(`最终结果: ${this.canMessages.length} 个消息, ${this.canSignals.length} 个信号`);
        
        // 返回解析统计供外部使用
        return parseStats;
    }

    // 添加调试面板
    addDebugPanel() {
        // 添加调试按钮
        const debugButton = document.createElement('button');
        debugButton.textContent = '调试状态';
        debugButton.className = 'btn btn-warning';
        debugButton.onclick = () => this.showDebugInfo();
        
        // 添加测试DBC文件按钮
        const testButton = document.createElement('button');
        testButton.textContent = '测试DBC文件';
        testButton.className = 'btn btn-info';
        testButton.onclick = () => this.loadTestDbcFile();
        
        const header = document.querySelector('.file-operations');
        if (header) {
            header.appendChild(debugButton);
            header.appendChild(testButton);
        }
    }

    // 加载测试DBC文件
    loadTestDbcFile() {
        // 创建一个隐藏的文件输入用于测试
        const testInput = document.createElement('input');
        testInput.type = 'file';
        testInput.accept = '.dbc';
        testInput.style.display = 'none';
        
        testInput.onchange = (e) => {
            const file = e.target.files[0];
            if (file) {
                console.log('开始解析DBC文件:', file.name);
                this.loadDbcFile(file);
            }
        };
        
        document.body.appendChild(testInput);
        testInput.click();
        document.body.removeChild(testInput);
    }

    // 显示调试信息
    showDebugInfo() {
        console.log('=== 调试信息 ===');
        console.log('选中消息ID:', this.selectedMessageId);
        console.log('所有消息:', this.canMessages);
        console.log('所有信号:', this.canSignals);
        
        if (this.selectedMessageId) {
            const selectedMessage = this.canMessages.find(m => m.id === this.selectedMessageId);
            console.log('选中的消息:', selectedMessage);
            
            const relatedSignals = this.canSignals.filter(s => s.messageId === this.selectedMessageId);
            console.log('相关信号:', relatedSignals);
        }
        
        // 检查DOM元素
        const signalTableBody = document.querySelector('#canSignalsTable tbody');
        console.log('信号表格DOM:', signalTableBody);
        console.log('信号表格行数:', signalTableBody ? signalTableBody.children.length : 'NULL');
    }

    // 下载DBC文件
    downloadDBC() {
        const content = document.getElementById('dbcContent').textContent;
        const blob = new Blob([content], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        
        const a = document.createElement('a');
        a.href = url;
        a.download = 'exported.dbc';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }
}

// 全局函数
function addCanMessage() {
    dbcEditor.addCanMessage();
}

function removeCanMessage() {
    dbcEditor.removeCanMessage();
}

function addCanSignal() {
    dbcEditor.addCanSignal();
}

function removeCanSignal() {
    dbcEditor.removeCanSignal();
}

function downloadDBC() {
    dbcEditor.downloadDBC();
}

function toggleFullscreen() {
    if (document.fullscreenElement) {
        document.exitFullscreen();
        document.body.classList.remove('fullscreen');
    } else {
        document.documentElement.requestFullscreen();
        document.body.classList.add('fullscreen');
    }
}

function toggleDbcPreview() {
    const preview = document.getElementById('dbcPreview');
    preview.style.display = preview.style.display === 'none' ? 'block' : 'none';
}

function calculatePhysicalValue() {
    dbcEditor.calculatePhysicalValue();
}

// 初始化编辑器
const dbcEditor = new DBCEditor();

// 添加CSS样式用于信号预览
const additionalStyles = `
.frame-layout,
.mask-layout {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.byte-row {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.byte-label {
    min-width: 60px;
    font-weight: 600;
    color: #2c3e50;
}

.bit-row {
    display: grid;
    grid-template-columns: repeat(8, 1fr);
    gap: 1px;
    background: #dee2e6;
    border-radius: 4px;
    overflow: hidden;
    min-width: 200px;
}

.bit-cell {
    background: white;
    padding: 0.5rem;
    text-align: center;
    font-weight: 600;
    font-size: 0.8rem;
    font-family: monospace;
}

.signal-bit {
    background: #4CAF50 !important;
    color: white;
}

.signal-mask {
    background: #2196F3 !important;
    color: white;
}

/* 状态提示样式 */
.loading {
    color: #3498db;
    font-style: italic;
}

.success {
    color: #27ae60;
    font-weight: bold;
}

.error {
    color: #e74c3c;
    font-weight: bold;
}

/* 文件上传区域样式 */
.file-drop-area {
    border: 2px dashed #3498db;
    border-radius: 8px;
    padding: 2rem;
    text-align: center;
    margin: 1rem 0;
    transition: all 0.3s ease;
}

.file-drop-area:hover {
    background: rgba(52, 152, 219, 0.1);
    border-color: #2980b9;
}

.file-drop-area.dragover {
    background: rgba(52, 152, 219, 0.2);
    border-color: #2980b9;
    transform: scale(1.02);
}
`;

// 动态添加CSS
const styleSheet = document.createElement('style');
styleSheet.textContent = additionalStyles;
document.head.appendChild(styleSheet);

// 添加拖拽上传功能
document.addEventListener('DOMContentLoaded', () => {
    const fileInput = document.getElementById('dbcFile');
    const body = document.body;

    // 防止默认拖拽行为
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        body.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    // 拖拽进入和离开的视觉反馈
    ['dragenter', 'dragover'].forEach(eventName => {
        body.addEventListener(eventName, highlight, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        body.addEventListener(eventName, unhighlight, false);
    });

    function highlight() {
        body.classList.add('dragover');
    }

    function unhighlight() {
        body.classList.remove('dragover');
    }

    // 处理文件拖拽
    body.addEventListener('drop', handleDrop, false);

    function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;

        if (files.length > 0) {
            const file = files[0];
            if (file.name.toLowerCase().endsWith('.dbc')) {
                dbcEditor.loadDbcFile(file);
            } else {
                alert('请选择.dbc文件！');
            }
        }
    }
}); 